import React, { useState } from 'react';
import { Form, InputNumber, Select, DatePicker, Input, Button, message, Space, Divider } from 'antd';
import { PlusOutlined, HistoryOutlined, FireOutlined, DashboardOutlined } from '@ant-design/icons';
import { WeightRecord } from '../types';
import { WeightAPI } from '../services/api';
import moment from 'moment';

const { Option } = Select;
const { TextArea } = Input;

interface WeightInputProps {
  onSuccess?: () => void;
  onGenerateMockData?: () => void;
}

const WeightInput: React.FC<WeightInputProps> = ({ onSuccess, onGenerateMockData }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [mockLoading, setMockLoading] = useState(false);

  // 提交体重记录
  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const record: Omit<WeightRecord, 'id' | 'created_at' | 'updated_at'> = {
        weight: values.weight,
        record_time: values.record_time ? values.record_time.toISOString() : new Date().toISOString(),
        record_type: values.record_type,
        note: values.note || ''
      };

      const response = await WeightAPI.addWeight(record);
      
      if (response.success) {
        message.success('🎉 记录成功！');
        form.resetFields();
        form.setFieldsValue({
          record_type: 'anytime',
          record_time: moment()
        });
        onSuccess?.();
      } else {
        message.error(response.error || '添加失败');
      }
    } catch (error: any) {
      message.error(error.error || '网络错误');
    } finally {
      setLoading(false);
    }
  };

  // 生成模拟数据
  const handleGenerateMockData = async () => {
    setMockLoading(true);
    try {
      const response = await WeightAPI.generateMockData();
      if (response.success) {
        message.success('测试数据生成成功！');
        onGenerateMockData?.();
      } else {
        message.error('生成失败');
      }
    } catch (error) {
      message.error('生成失败');
    } finally {
      setMockLoading(false);
    }
  };

  return (
    <div className="weight-input-section">
      <div style={{ 
        marginBottom: '12px',
        padding: '12px',
        backgroundColor: 'rgba(26, 26, 46, 0.95)',
        border: '1px solid #2d4a6b',
        borderRadius: '8px',
        boxShadow: '0 2px 12px rgba(0,0,0,0.3)'
      }}>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          marginBottom: '12px'
        }}>
          <h3 style={{ 
            margin: 0, 
            color: '#fff',
            fontSize: '14px',
            fontWeight: 'bold'
          }}>
            陈伟基减肥日记
          </h3>
          <Button 
            type="primary" 
            size="small"
            onClick={handleGenerateMockData}
            style={{ 
              backgroundColor: '#00da3c',
              borderColor: '#00da3c',
              fontSize: '10px',
              height: '20px',
              padding: '0 6px'
            }}
          >
            测试数据
          </Button>
        </div>

        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            record_type: 'anytime',
            record_time: moment()
          }}
        >
          {/* 体重输入 */}
          <Form.Item
            label={<span style={{ color: '#999', fontSize: '10px' }}>💪 当前体重</span>}
            name="weight"
            rules={[{ required: true, message: '请输入体重' }]}
            style={{ marginBottom: '8px' }}
          >
            <InputNumber
              placeholder="输入体重"
              min={30}
              max={200}
              step={0.1}
              precision={1}
              size="large"
              style={{ 
                width: '100%',
                backgroundColor: '#1a1a1a',
                borderColor: '#555',
                color: '#fff'
              }}
              addonAfter="kg"
            />
          </Form.Item>

          {/* 记录类型 */}
          <Form.Item
            label={<span style={{ color: '#999', fontSize: '10px' }}>⏰ 记录时机</span>}
            name="record_type"
            style={{ marginBottom: '8px' }}
          >
            <Select size="large" style={{ backgroundColor: '#1a1a1a' }}>
              <Option value="morning">🌅 早晨</Option>
              <Option value="evening">🌙 晚上</Option>
              <Option value="anytime">⚡ 随时</Option>
            </Select>
          </Form.Item>

          {/* 时间选择 */}
          <Form.Item
            label={<span style={{ color: '#999', fontSize: '10px' }}>📅 记录时间</span>}
            name="record_time"
            style={{ marginBottom: '8px' }}
          >
            <DatePicker
              showTime
              format="YYYY-MM-DD HH:mm"
              placeholder="选择时间"
              size="large"
              style={{ 
                width: '100%',
                backgroundColor: '#1a1a1a',
                borderColor: '#555'
              }}
            />
          </Form.Item>

          {/* 备注 */}
          <Form.Item
            label={<span style={{ color: '#999', fontSize: '10px' }}>📝 备注</span>}
            name="note"
            style={{ marginBottom: '12px' }}
          >
            <TextArea
              placeholder="记录心情或原因..."
              rows={1}
              style={{
                backgroundColor: '#1a1a1a',
                borderColor: '#555',
                color: '#fff',
                resize: 'none'
              }}
            />
          </Form.Item>

          {/* 提交按钮 */}
          <Form.Item style={{ marginBottom: '0' }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              size="large"
              block
              icon={<FireOutlined />}
              style={{
                background: 'linear-gradient(135deg, #00da3c 0%, #00a82d 100%)',
                border: 'none',
                borderRadius: '4px',
                fontWeight: 'bold',
                height: '32px'
              }}
            >
              {loading ? '记录中...' : '🚀 添加记录'}
            </Button>
          </Form.Item>
        </Form>

        {/* 提示信息 */}
        <Divider style={{ margin: '8px 0', borderColor: '#444' }} />
        <div style={{
          fontSize: '9px',
          color: '#666',
          lineHeight: '1.2'
        }}>
          💡 每次记录都会影响K线图的开收盘价和高低点
        </div>
      </div>
    </div>
  );
};

export default WeightInput;